package com.share.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.common.core.exception.ServiceException;
import com.share.common.security.utils.SecurityUtils;
import com.share.device.domain.PowerBank;
import com.share.device.mapper.PowerBankMapper;
import com.share.device.service.IPowerBankService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;

@Service
public class PowerBankServiceImpl extends ServiceImpl<PowerBankMapper, PowerBank> implements IPowerBankService
{

    @Autowired
    private PowerBankMapper powerBankMapper;

    @Override
    public List<PowerBank> selectListPowerBank(PowerBank powerBank) {
        return powerBankMapper.selectListPowerBank(powerBank);
    }

    @Override
    public int savePowerBank(PowerBank powerBank) {
        //1.设置相关数值
        powerBank.setUpdateBy(SecurityUtils.getUsername());
        powerBank.setCreateTime(new Date());
        powerBank.setUpdateTime(new Date());

        //2.判断powerBankNo是否存在，如果存在才做添加
        String powerBankNo = powerBank.getPowerBankNo();
        LambdaQueryWrapper<PowerBank> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PowerBank::getPowerBankNo, powerBankNo);
        Long count = powerBankMapper.selectCount(queryWrapper);
        if (count > 0){ //如果存在不进行添加
            throw new ServiceException("充电宝编号已存在");
        }
        //2.添加
        int insert = powerBankMapper.insert(powerBank);
        return insert;
    }

    @Override
    public int updatePowerBank(PowerBank powerBank) {
        //1.判断状态是0才进行修改
        Long id = powerBank.getId();
        PowerBank oldPowerBank = powerBankMapper.selectById(id);
        if (oldPowerBank != null && "0".equals(oldPowerBank.getStatus())) {
            int i = powerBankMapper.updateById(powerBank);
            return i;
        }
        return 0;
    }
}